package com.jingbit.ai.helper;

import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;

import com.jingbit.ai.entities.CallLogInfo;
import com.jingbit.ai.entities.ContactInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@SuppressLint("NewApi")
public class ContactHelper {
	/**
	 * 读取通话记录
	 * 
	 * @return 读取到的数据
	 */
	public static void getCallLogs(Context context, Callback callback) {
		// 1.获得ContentResolver
		ContentResolver resolver = context.getContentResolver();
		// 2.利用ContentResolver的query方法查询通话记录数据库
		/**
		 * @param uri
		 *            需要查询的URI，（这个URI是ContentProvider提供的）
		 * @param projection
		 *            需要查询的字段
		 * @param selection
		 *            sql语句where之后的语句
		 * @param selectionArgs
		 *            ?占位符代表的数据
		 * @param sortOrder
		 *            排序方式
		 * 
		 */
		String selection = null;
		String[] selectionArgs = null;
//		if (BaseApplication.lastUpload2 > 0) {
//			selection = CallLog.Calls.DATE + ">?";
//			selectionArgs = new String[]{String.valueOf(BaseApplication.lastUpload2)};
//		}
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
				new String[] { CallLog.Calls.CACHED_NAME// 通话记录的联系人
						, CallLog.Calls.NUMBER// 通话记录的电话号码
						, CallLog.Calls.DATE// 通话记录的日期
						, CallLog.Calls.DURATION// 通话时长
						, CallLog.Calls.TYPE }// 通话类型
				, selection, selectionArgs, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
		);
		// 3.通过Cursor获得数据
		List<CallLogInfo> list = new ArrayList<CallLogInfo>();
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
			String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
			long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
			String date = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date(dateLong));
			int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
			int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
			String typeString = "";
			switch (type) {
			case CallLog.Calls.INCOMING_TYPE:
				typeString = "接入";
				break;
			case CallLog.Calls.OUTGOING_TYPE:
				typeString = "拨出";
				break;
			case CallLog.Calls.MISSED_TYPE:
				typeString = "未接";
				break;
			default:
				break;
			}
			CallLogInfo callLogInfo=new CallLogInfo();
			callLogInfo.setName(name);
			callLogInfo.setPhoneno(number);
			callLogInfo.setDuration( (duration / 60) + "分钟");
			callLogInfo.setType(typeString);
			callLogInfo.setDate(date);

			list.add(callLogInfo);
		}
		Message msg = Message.obtain();
		msg.what=1;
		msg.obj = list;
		callback.handleMessage(msg);
	}

	/**
	 * 获取联系人 初始化数据库查询参数
	 */
	public static void getContacts(Context context, Callback callback) {
		MyAsyncQueryHandler asyncQueryHandler = new MyAsyncQueryHandler(context.getContentResolver(), callback);
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri；
		// 查询的字段
		String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1,
				"sort_key", ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY };
		String selection = null;
		String[] selectionArgs = null;
//		if (BaseApplication.lastUpload1 > 0) {
//			selection = ContactsContract.CommonDataKinds.Phone.DATA1 + ">?";
//			selectionArgs = new String[]{String.valueOf(BaseApplication.lastUpload1)};
//		}
		// 按照sort_key升序查詢
		asyncQueryHandler.startQuery(0, null, uri, projection, selection, selectionArgs, "sort_key COLLATE LOCALIZED asc");
	}

	private static class MyAsyncQueryHandler extends AsyncQueryHandler {
		private Callback callback;

		public MyAsyncQueryHandler(ContentResolver cr, Callback callback) {
			super(cr);
			this.callback = callback;
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			List<ContactInfo> list = new ArrayList<ContactInfo>();
			if (cursor != null && cursor.getCount() > 0) {
				HashMap<Integer, ContactInfo> contactIdMap = new HashMap<Integer, ContactInfo>();
				cursor.moveToFirst(); // 游标移动到第一项
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					String name = cursor.getString(1);
					String number = cursor.getString(2);
					String sortKey = cursor.getString(3);
					int contactId = cursor.getInt(4);
					Long photoId = cursor.getLong(5);
					String lookUpKey = cursor.getString(6);

					if (contactIdMap.containsKey(contactId)) {
						// 无操作
					} else {
						// 创建联系人对象
						ContactInfo contact = new ContactInfo();
						contact.setName(name);
						contact.setMobile(number);
						list.add(contact);
						contactIdMap.put(contactId, contact);
					}
				}
			}
			Message msg = Message.obtain();
			msg.obj = list;
			callback.handleMessage(msg);
		}
	}

}
